package org.hose.util;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import org.hose.core.TestCase;
import org.hose.core.TestCaseStep;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class ExcelUtils {

    /**
     * 从Excel中读取测试用例
     *
     * @param filePath
     * @param sheetName
     * @return
     */
    public static List<TestCase> readTestCase(String filePath, String sheetName) {
        // 假设您的Excel文件有一个工作表名为"Sheet1"，第一列是输入数据，第二列是预期输出
        ExcelReader reader;
        if (StrUtil.isBlank(sheetName)) {
            reader = ExcelUtil.getReader(filePath);
        } else {
            reader = ExcelUtil.getReader(filePath, sheetName);
        }
        List<Map<String, Object>> maps = reader.readAll();
        reader.close();
        // TreeMap 用于按顺序存储测试用例
        TreeMap<String, TestCase> testDataMap = new TreeMap<>();
        for (Map<String, Object> map : maps) {
            TestCase testCase = testDataMap.get(map.get("用例编号").toString());
            if (testCase == null) {
                testCase = new TestCase();
                testCase.setCaseId(map.get("用例编号").toString());
                testCase.setCaseName((String) map.get("用例名称"));
                testCase.setModule((String) map.get("模块"));
                testDataMap.put(map.get("用例编号").toString(), testCase);
            }
            // String description, String command, String targetElement, String parameter
            TestCaseStep caseStep = new TestCaseStep(MapUtil.getStr(map, "步骤", "|- 空步骤"), MapUtil.getStr(map, "操作"), MapUtil.getStr(map, "元素"), MapUtil.getStr(map, "数据"));
            testCase.getSteps().add(caseStep);
        }
        return ListUtil.toList(testDataMap.values());
    }

}
